package com.vvlive.caibao.smartcity.app;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.vvlive.caibao.smartcity.bean.Dept;
import com.vvlive.caibao.smartcity.bean.Friend;
import com.vvlive.caibao.smartcity.bean.MeetingRoom;
import com.vvlive.caibao.smartcity.bean.User;
import com.vvlive.caibao.smartcity.utils.RongUtil;
import com.vvlive.caibao.smartcity.utils.TimeUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.imkit.RongIM;

/**
 * Created by zhj on 2015/6/30.
 */
public class SmartCityApp extends Application {

    public static final class Constants {
        public static final String TAG = "SmartCity";
    }

    public static Context context;
    public static User currentUser;
    public static List<Friend> friends;

    public static List<Dept> deptList;
    public static List<MeetingRoom> meetingRoomList;

    /**
     * 是否登录
     */
    public static boolean isLogin = false;


    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        CrashHandler crashHandler = CrashHandler.getInstance();
//        crashHandler.init();
        RongIM.init(this);
        String token = "BjAdO9EyYiZowCUOdfBop8HwoVvlDqBE7KbFx76m7U1wsAuC+KW6ZPED+NOhRj/KnfAvoY5CO4epvfbkxxPO5qV69nCCOuKi";
        try {
            RongUtil.getInstance().connect(token, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自定义程序闪退处理
     * （来自互联网）
     */
    private static final class CrashHandler implements Thread.UncaughtExceptionHandler {

        private final int EXCEPTION_CODE = 0000;
        //系统默认的UncaughtException处理类
        private Thread.UncaughtExceptionHandler mDefaultHandler;
        //用来存储设备信息和异常信息
        private Map<String, String> infos = new HashMap<String, String>();

        /**
         * 保证只有一个CrashHandler实例
         */
        private CrashHandler() {
        }

        private static CrashHandler instance;

        public static CrashHandler getInstance() {
            return instance != null ? instance : new CrashHandler();
        }

        public void init() {
            //获取系统默认的UncaughtException处理器
            mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
            //设置该CrashHandler为程序的默认处理器
            Thread.setDefaultUncaughtExceptionHandler(this);
        }

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            if (!handleException(ex) && mDefaultHandler != null) {
                //如果用户没有处理则让系统默认的异常处理器来处理
                mDefaultHandler.uncaughtException(thread, ex);
            } else {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    Log.e(Constants.TAG, "error : ", e);
                }
                //退出程序
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);
            }
        }

        /**
         * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
         *
         * @param ex
         * @return true:如果处理了该异常信息;否则返回false.
         */
        private boolean handleException(final Throwable ex) {
            if (ex == null) {
                return false;
            }
            //使用Toast来显示异常信息
            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
//                    handler.sendMessage(handler.obtainMessage(EXCEPTION_CODE, ex.getMessage()));
                    Toast.makeText(context, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }.start();
            //收集设备参数信息
            collectDeviceInfo(context);
            //保存日志文件
            saveCrashInfo2File(ex);
            return true;
        }

        /**
         * 收集设备参数信息
         *
         * @param ctx
         */
        public void collectDeviceInfo(Context ctx) {
            try {
                PackageManager pm = ctx.getPackageManager();
                PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
                if (pi != null) {
                    String versionName = pi.versionName == null ? "null" : pi.versionName;
                    String versionCode = pi.versionCode + "";
                    infos.put("versionName", versionName);
                    infos.put("versionCode", versionCode);
                }
            } catch (PackageManager.NameNotFoundException e) {
                Log.e(Constants.TAG, "an error occured when collect package info", e);
            }
            Field[] fields = Build.class.getDeclaredFields();
            for (Field field : fields) {
                try {
                    field.setAccessible(true);
                    infos.put(field.getName(), field.get(null).toString());
                    Log.d(Constants.TAG, field.getName() + " : " + field.get(null));
                } catch (Exception e) {
                    Log.e(Constants.TAG, "an error occured when collect crash info", e);
                }
            }
        }

        /**
         * 保存错误信息到文件中
         *
         * @param ex
         * @return 返回文件名称, 便于将文件传送到服务器
         */
        private String saveCrashInfo2File(Throwable ex) {

            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> entry : infos.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sb.append(key + "=" + value + "\n");
            }

            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            ex.printStackTrace(printWriter);
            Throwable cause = ex.getCause();
            while (cause != null) {
                cause.printStackTrace(printWriter);
                cause = cause.getCause();
            }
            printWriter.close();
            String result = writer.toString();
            sb.append(result);
            try {
                long timestamp = System.currentTimeMillis();
                String time = TimeUtil.getCurrentTime();
                String fileName = "crash-" + time + "-" + timestamp + ".log";
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    String path = "/sdcard/crash/";
                    File dir = new File(path);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(path + fileName);
                    fos.write(sb.toString().getBytes());
                    fos.close();
                }
                return fileName;
            } catch (Exception e) {
                Log.e(Constants.TAG, "an error occured while writing file...", e);
            }
            return null;
        }
    }
}
